﻿using Microsoft.AspNetCore.Identity;
using OpenIddict.Abstractions;
using WT.OpenIddict.Domain.Shared.LifeTime;
using WT.OpenIddict.Domain.User;

namespace WT.OpenIddict.Domain.Manager.TokenManager;

public class TokenManager : DomainService, ITokenManager
{
    private readonly IOpenIddictTokenManager _tokenManager;
    private readonly UserManager<UserDetails> _userManager;

    public TokenManager(IOpenIddictTokenManager tokenManager, UserManager<UserDetails> userManager)
    {
        _tokenManager = tokenManager;
        _userManager = userManager;
    }

    public async Task RevocateAllTokensAsyncByUserId(string userId)
    {
        var token = await _tokenManager.FindBySubjectAsync(userId).ToListAsync();
        foreach (var tokenDetails in token) await _tokenManager.TryRevokeAsync(tokenDetails);
    }

    public async Task RevocateAllTokensAsyncByApplicationId(string applicationId)
    {
        var token = await _tokenManager.FindByApplicationIdAsync(applicationId).ToListAsync();
        foreach (var tokenDetails in token) await _tokenManager.TryRevokeAsync(tokenDetails);
    }

    public async Task RevocateTokenAsnycByUserIdRecentlest(string userId)
    {
        var tokens = await _tokenManager.FindBySubjectAsync(userId).ToListAsync();
        var newestToken = tokens.LastOrDefault();
        if (newestToken == null) return;
        await _tokenManager.TryRevokeAsync(newestToken);
    }
}